// cloudfunctions/manageprinters/index.js
const cloud = require('wx-server-sdk');
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV });
const db = cloud.database();

// --- *** 新增：管理员 OPENID *** ---
const ADMIN_OPENID = '41b03074e1bb154e164f0a56873bf6d0';

/**
 * 入口函数
 * @param {object} event - 包含 action (操作类型), printerId (打印机ID), data (操作数据)
 */
exports.main = async (event, context) => {
  const { action, printerId, data } = event;

  // --- *** 新增：权限校验 *** ---
  const wxContext = cloud.getWXContext();
  const openid = wxContext.OPENID;

  if (openid !== ADMIN_OPENID) {
    return {
      success: false,
      message: '无权操作'
    };
  }
  // --- *** 权限校验结束 *** ---

  try {
    switch (action) {
      case 'add':
        // 添加新打印机
        if (!data || !data.name || !data.location) {
           return { success: false, message: '缺少必要参数' };
        }
        return await db.collection('printers').add({
          data: {
            name: data.name,
            location: data.location,
            status: data.status || '正常', // 默认为正常
            remark: data.remark || ''
          }
        });

      case 'updateStatus':
        // 更新打印机状态
        if (!printerId || !data || !data.status) {
          return { success: false, message: '缺少必要参数' };
        }
        return await db.collection('printers').doc(printerId).update({
          data: {
            status: data.status
          }
        });

      case 'delete':
        // 删除打印机 (您之前的文件中没有，我为您加上)
        if (!printerId) {
          return { success: false, message: '缺少 printerId' };
        }
        return await db.collection('printers').doc(printerId).remove();
      
      // --- *** 新增：获取所有打印机 (管理专用) *** ---
      case 'getAdminList':
        return await db.collection('printers').orderBy('name', 'asc').get();

      default:
        return {
          success: false,
          message: '未知的操作类型'
        }
    }
  } catch (e) {
    console.error('操作打印机失败', e);
    return {
      success: false,
      error: e
    }
  }
};